package com.me.test.controller;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 */
@Controller
public class ReadLibApi {

    /**
     * SpringBoot 读取 jar包里的文件：http://localhost:8888/readLibInJar?path=BOOT-INF/lib/druid-1.2.6.jar
     *
     * TODO ClassPathResource 带不带 "/" 都以 classpath 为相对路径，但是 `BOOT-INF/lib/druid-1.2.6.jar` 可以读取 lib jar
     */
    @GetMapping(value = "readLibInJar", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> readFileInJar(String path) throws IOException {
        ClassPathResource resource = new ClassPathResource(path);
        System.out.println(resource.getURL());
        InputStream inputStream = resource.getInputStream();
        byte[] data = IOUtils.toByteArray(inputStream);

        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment; filename=" + resource.getFilename())
                .contentLength(data.length)
                .body(data);
    }

}
